<template>
  <div class="mainDiv">
    <el-row class="contentDiv mb-10"
      ><el-row
        type="flex"
        justify="space-between"
        align="middle"
        class="mb-10"
      >
        <el-col
          :span="7"
          class="flexCenter"
        >
          盘点名称：<el-input
            :disabled="draftBtnStatus ? true : false"
            style="flex: 1"
            placeholder="请输入盘点名称"
            v-model="stockName"
          ></el-input
        ></el-col>
        <el-col
          :span="7"
          class="flexCenter"
        >
          盘点单号：<el-input
            :disabled="draftBtnStatus ? true : false"
            style="flex: 1"
            placeholder="请输入盘点单号"
            v-model="orderNum"
          ></el-input
        ></el-col>
        <el-col
          :span="7"
          class="flexCenter"
        >
          领用人：
          <el-select
            :disabled="draftBtnStatus ? true : false"
            style="flex: 1"
            placeholder="请选择领用人"
            v-model="recipient"
            @focus="getEnableUserListApi"
          >
            <el-option
              v-for="el in manOptions"
              :key="el.id"
              :label="el.name"
              :value="el.id"
            >
            </el-option>
          </el-select>
        </el-col>
      </el-row>
      <el-row
        type="flex"
        justify="space-between"
        align="middle"
        class="mb-10"
      >
        <el-col
          :span="7"
          class="flexCenter"
          >盘点日期：
          <el-date-picker
            :disabled="draftBtnStatus ? true : false"
            style="flex: 1; margin: 0"
            v-model="stockDate"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="选择开始日期"
            end-placeholder="选择结束日期"
          >
          </el-date-picker
        ></el-col>
        <el-col :span="7"></el-col>
        <el-col :span="7"></el-col>
      </el-row>
      <el-row
        type="flex"
        justify="space-between"
        align="middle"
      >
        <el-col
          :xl="16"
          :lg="16"
          :md="16"
          :xs="24"
        >
          <el-button
            type="primary"
            @click="addHandler"
            >新增</el-button
          >
          <el-button
            :disabled="draftBtnStatus ? true : false"
            type="warning"
            @click="auditHandler()"
            >审核</el-button
          >
          <el-button
            :disabled="draftBtnStatus ? true : false"
            type="warning"
            @click="exportHandler"
            >批量导出</el-button
          >
          <el-button
            :disabled="draftBtnStatus ? true : false"
            type="primary"
            @click="shuaxin"
            >刷新</el-button
          >
        </el-col>
        <el-col
          :span="7"
          class="text-r"
        >
          <el-button
            :type="draftBtnStatus ? 'danger' : 'primary'"
            style="width: 120px"
            @click="draftBtnStatusHandler"
            >{{ draftBtnStatus ? '关闭草稿箱' : '草稿箱' }}</el-button
          >
          <el-button
            :disabled="draftBtnStatus ? true : false"
            type="primary"
            @click="searchHandler"
            >查询</el-button
          ><el-button
            plain
            :disabled="draftBtnStatus ? true : false"
            @click="resetHandler"
            >重置</el-button
          ></el-col
        >
      </el-row></el-row
    >
    <el-row class="contentDiv mb-10">
      <el-table
        :data="renderData"
        border
        style="width: 100%"
        height="685"
        :header-cell-style="{ 'text-align': 'center' }"
        :cell-style="{ 'text-align': 'center' }"
        @selection-change="handleSelectionChange"
        ref="multipleTable"
        :row-key="(row) => row.id"
      >
        <el-table-column
          type="selection"
          width="55"
          reserve-selection
        >
        </el-table-column>
        <el-table-column
          type="index"
          label="序号"
          width="50"
          align="center"
        />
        <el-table-column
          prop="stateName"
          label="审批状态"
          min-width="110"
        >
          <template slot-scope="scope">
            <span
              v-if="scope.row.state === 'draft'"
              class="text-info"
            >
              <span class="circleSpan">{{ scope.row.stateName }}</span>
            </span>
            <span
              v-else-if="scope.row.state === 'completed'"
              class="text-success"
            >
              <span class="circleSpan">{{ scope.row.stateName }}</span>
            </span>
            <span
              v-else-if="scope.row.state === 'terminated'"
              class="text-danger"
            >
              <span class="circleSpan">{{ scope.row.stateName }}</span>
            </span>
            <span
              v-else
              class="text-primary"
            >
              <span class="circleSpan">{{ scope.row.stateName }}</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="orderNum"
          label="盘点单号"
          align="center"
          min-width="150"
        >
        </el-table-column>
        <el-table-column
          prop="stockName"
          label="盘点名称"
          align="center"
          min-width="150"
        >
          <template slot-scope="scope">
            <div v-if="scope.row.stockName">
              {{ scope.row.stockName }}
            </div>
            <div
              v-else
              class="noFile"
            >
              暂未填写
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="storeName"
          label="仓库名称"
          align="center"
          min-width="150"
        >
          <template slot-scope="scope">
            <div v-if="scope.row.storeName">
              {{ scope.row.storeName }}
            </div>
            <div
              v-else
              class="noFile"
            >
              暂未填写
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="remark"
          label="备注"
          align="center"
          min-width="150"
        >
          <template slot-scope="scope">
            <div v-if="scope.row.remark">
              {{ scope.row.remark }}
            </div>
            <div
              v-else
              class="noFile"
            >
              暂未填写
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="stockDate"
          label="盘点日期"
          align="center"
          min-width="150"
        >
        </el-table-column
        ><el-table-column
          prop="recipientName"
          label="领用人"
          min-width="150"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="preparedName"
          label="制单人"
          align="center"
        >
        </el-table-column>

        <el-table-column
          fixed="right"
          label="操作"
          width="150"
        >
          <template slot-scope="scope">
            <el-button
              v-if="draftBtnStatus == false"
              type="text"
              @click="detailHandler(scope.row)"
              >详情</el-button
            >
            <el-button
              v-if="scope.row.permission && scope.row.state == 'draft'"
              type="text"
              @click="editHandler(scope.row)"
              >编辑</el-button
            >

            <el-button
              v-if="scope.row.permission && scope.row.state == 'draft'"
              type="text"
              style="color: red"
              @click="deleteTeamTakeStockApi(scope.row.id)"
              >删除</el-button
            >
          </template> </el-table-column
        ><template #empty>
          <el-empty v-loading="loading"></el-empty>
        </template>
      </el-table>
    </el-row>
    <el-row class="contentDiv text-r">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[10, 20, 50]"
        :page-size="10"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-row>
    <!-- 新增/编辑 -->
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :title="editTitle"
      :visible.sync="editDialogStatus"
      :fullscreen="true"
      :modal="false"
    >
      <div
        :style="{
          width: editTitle === '详情' && isDraft === false ? '70%' : '100%',
        }"
        class="dialogItem"
      >
        <el-form
          :model="editForm"
          :rules="rules"
          ref="editForm"
          label-width="100px"
          :style="{
            width: editTitle === '详情' && isDraft === false ? '100%' : '80%',
          }"
          style="margin: 0 auto"
        >
          <el-row class="mb-10 text-primary">基础信息</el-row>
          <el-row class="mb-10">
            <el-col :span="8">
              <el-form-item
                label="盘点名称："
                prop="stockName"
              >
                <el-input
                  :disabled="editTitle === '详情'"
                  v-model="editForm.stockName"
                  placeholder="请输入盘点名称"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="领用人："
                prop="recipient"
              >
                <el-select
                  :disabled="editTitle === '详情'"
                  v-model="editForm.recipient"
                  placeholder="请选择"
                  style="width: 100%"
                  @focus="getEnableUserListApi"
                  @change="getTeamTakeStockGetItemApi"
                >
                  <el-option
                    v-for="item in manOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="盘点日期："
                prop="stockDate"
              >
                <el-date-picker
                  :disabled="editTitle === '详情'"
                  style="width: 100%"
                  v-model="editForm.stockDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="mb-10">
            <el-col :span="8">
              <el-form-item
                label="仓库名称："
                prop="storeId"
              >
                <el-select
                  :disabled="editTitle === '详情'"
                  v-model="editForm.storeId"
                  placeholder="请选择"
                  style="width: 100%"
                  @focus="getStoreMgListApi"
                  @change="getTeamTakeStockGetItemApi"
                >
                  <el-option
                    v-for="item in storeOptions"
                    :key="item.id"
                    :label="item.storeName"
                    :value="item.id"
                  >
                  </el-option> </el-select
              ></el-form-item> </el-col
            ><el-col :span="8">
              <el-form-item label="备注：">
                <el-input
                  v-model="editForm.remark"
                  :disabled="editTitle === '详情'"
                  type="textarea"
                  placeholder="请输入备注"
                ></el-input>
              </el-form-item> </el-col
          ></el-row>
          <el-row class="mb-10">
            <el-col :span="16">
              <el-button
                v-if="editTitle !== '详情'"
                type="primary"
                @click="openInnerDialog"
                >新增</el-button
              >
              <el-button
                v-if="editTitle !== '详情'"
                type="danger"
                @click="deteleRowHandler"
                >删除</el-button
              >
            </el-col>
          </el-row>
          <el-row class="mb-10 text-primary">盘点信息</el-row>
          <el-row>
            <el-form-item
              label-width="0"
              prop="teamTakeStockItems"
              ><el-table
                :data="editForm.teamTakeStockItems"
                style="width: 100%; min-height: 600px"
                element-loading-text="Loading"
                element-loading-spinner="el-icon-loading"
                :header-cell-style="{ 'text-align': 'center' }"
                :cell-style="{ 'text-align': 'center' }"
                @selection-change="getChange($event, 'list')"
                :row-key="getRowKey"
                ref="listTable"
              >
                <el-table-column
                  type="selection"
                  width="55"
                  v-if="editTitle != '详情'"
                />
                <el-table-column
                  type="index"
                  label="序号"
                  width="55"
                />

                <el-table-column
                  prop="supplierName"
                  label="供应商"
                  min-width="150"
                >
                </el-table-column>
                <el-table-column
                  prop="batchNum"
                  label="批号"
                  min-width="150"
                >
                </el-table-column>
                <el-table-column
                  prop="materialName"
                  label="物料名称"
                  min-width="150"
                >
                </el-table-column>
                <el-table-column
                  prop="modelName"
                  label="规格型号"
                  min-width="150"
                >
                </el-table-column>
                <el-table-column
                  label="计量单位"
                  prop="unit"
                >
                </el-table-column>
                <el-table-column
                  label="库存合计"
                  min-width="150"
                >
                  <template slot-scope="scope">
                    <span
                      v-if="scope.row.totalInventory && editTitle === '详情'"
                      >{{ scope.row.totalInventory }}</span
                    ><el-form-item
                      v-else
                      :prop="
                        'teamTakeStockItems.' + scope.$index + '.totalInventory'
                      "
                      :rules="stotalInventoryRules"
                      label-width="0"
                    >
                      <el-input-number
                        :disabled="editTitle === '详情'"
                        style="width: 100%"
                        v-model="scope.row.totalInventory"
                        :max="9999999"
                        :precision="2"
                        label="0"
                        :controls="false"
                      ></el-input-number
                    ></el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="本月原材料库存"
                  min-width="150"
                >
                  <template slot-scope="scope">
                    <span
                      v-if="scope.row.materialInventory && editTitle === '详情'"
                      >{{ scope.row.materialInventory }}</span
                    ><el-form-item
                      v-else
                      :prop="
                        'teamTakeStockItems.' +
                        scope.$index +
                        '.materialInventory'
                      "
                      :rules="materialInventoryRules"
                      label-width="0"
                      ><el-input-number
                        :disabled="editTitle === '详情'"
                        style="width: 100%"
                        v-model="scope.row.materialInventory"
                        :max="9999999"
                        :precision="2"
                        label="0"
                        :controls="false"
                      ></el-input-number
                    ></el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="本月成品及半成品库存"
                  min-width="170"
                >
                  <template slot-scope="scope">
                    <span
                      v-if="
                        scope.row.manufacturedInventory && editTitle === '详情'
                      "
                      >{{ scope.row.manufacturedInventory }}</span
                    ><el-form-item
                      v-else
                      :prop="
                        'teamTakeStockItems.' +
                        scope.$index +
                        '.manufacturedInventory'
                      "
                      :rules="manufacturedInventoryRules"
                      label-width="0"
                    >
                      <el-input-number
                        :disabled="editTitle === '详情'"
                        style="width: 100%"
                        v-model="scope.row.manufacturedInventory"
                        :max="9999999"
                        :precision="2"
                        :controls="false"
                      ></el-input-number
                    ></el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="累计领用量"
                  min-width="150"
                >
                  <template slot-scope="scope">
                    <span
                      v-if="scope.row.totalVolume && editTitle === '详情'"
                      >{{ scope.row.totalVolume }}</span
                    ><el-form-item
                      v-else
                      :prop="
                        'teamTakeStockItems.' + scope.$index + '.totalVolume'
                      "
                      :rules="totalVolumeRules"
                      label-width="0"
                    >
                      <el-input-number
                        :disabled="editTitle === '详情'"
                        style="width: 100%"
                        v-model="scope.row.totalVolume"
                        :max="9999999"
                        :precision="2"
                        label="0"
                        :controls="false"
                      ></el-input-number
                    ></el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="备注"
                  min-width="120"
                  prop="remark"
                >
                  <template slot-scope="scope">
                    <span
                      v-if="
                        scope.row.remark ||
                        (scope.row.remark === '' && editTitle === '详情')
                      "
                      >{{
                        scope.row.remark === '' ? '/' : scope.row.remark
                      }}</span
                    >
                    <el-form-item
                      label-width="0"
                      v-else
                    >
                      <el-input
                        v-model="scope.row.remark"
                        :disabled="editTitle === '详情'"
                      ></el-input
                    ></el-form-item>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </el-row>
        </el-form>
        <el-row
          type="flex"
          justify="center"
          slot="footer"
        >
          <div v-if="editTitle === '详情'">
            <el-button
              v-if="editForm.permission && editForm.state !== 'draft'"
              type="warning"
              @click="auditHandler('detail', editForm)"
              >审核</el-button
            >
            <el-button @click="editDialogStatus = false">返回</el-button>
          </div>
          <div v-else>
            <el-button
              v-if="editTitle === '新增'"
              type="primary"
              @click="saveDraftHandler('editForm')"
              >保存草稿</el-button
            >
            <el-button
              type="primary"
              @click="submitHandler('editForm')"
              >提交</el-button
            >
            <el-button @click="cancelHandler('editForm')">取消</el-button>
          </div>
        </el-row>
      </div>
      <el-dialog
        width="50%"
        title="选择盘点数据"
        :visible.sync="innerVisible"
        :modal="false"
      >
        <el-row class="mb-10">
          <el-table
            :data="teamTakeStockItems"
            style="width: 100%; min-height: 600px"
            element-loading-text="Loading"
            element-loading-spinner="el-icon-loading"
            :header-cell-style="{ 'text-align': 'center' }"
            :cell-style="{ 'text-align': 'center' }"
            @selection-change="getChange($event, 'select')"
            @row-click="innerRowClickHandler"
            :row-key="getRowKey"
            ref="selectTable"
          >
            <el-table-column
              type="selection"
              :reserve-selection="true"
              width="55"
            />
            <el-table-column
              type="index"
              label="序号"
              width="55"
            />
            <el-table-column
              prop="supplierName"
              label="供应商"
              min-width="150"
            ></el-table-column>
            <el-table-column
              prop="batchNum"
              label="批号"
              min-width="150"
            ></el-table-column>
            <el-table-column
              prop="materialName"
              label="物料名称"
              min-width="150"
            ></el-table-column>
            <el-table-column
              prop="modelName"
              label="规格型号"
              min-width="150"
            ></el-table-column>
          </el-table>
        </el-row>
        <el-row
          type="flex"
          justify="center"
          slot="footer"
        >
          <el-button @click="innerVisible = false">返回</el-button>
        </el-row>
      </el-dialog>
      <div
        v-if="editTitle === '详情' && isDraft === false"
        style="width: calc(30% - 20px); height: 100%; margin-left: 20px"
        class="dialogItem"
      >
        <approxFlow
          ref="approxFlow"
          :steps="steps"
        ></approxFlow>
      </div>
    </el-dialog>
    <el-dialog
      width="30%"
      title="选择抄送人"
      :visible.sync="ccListStatus"
      append-to-body
      :destroy-on-close="true"
    >
      <div>
        <soan>抄送人</soan>
        <el-select
          v-model="ccList"
          placeholder="请选择抄送人"
          style="width: 100%"
          multiple
        >
          <el-option
            v-for="item in manOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </div>

      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="ccListStatus = false">取 消</el-button>
        <el-button
          type="primary"
          @click="ccListSumbit"
          >确认提交</el-button
        >
      </div>
    </el-dialog>
    <toExamine
      ref="toExamine"
      :steps="steps"
      :approxForm="approxForm"
      :toExamineData="toExamineData"
    ></toExamine>
  </div>
</template>

<script>
import {
  getTeamTakeStockPage,
  addTeamTakeStock,
  addTeamTakeStockDraft,
  updateTeamTakeStockDraft,
  deleteTeamTakeStock,
  getTeamTakeStockDetail,
  getTeamTakeStockGetItem,
  getTeamTakeStockExport,
  terminatePlan,
  executeTaskPlan,
} from '/src/http/materialDispatch/stockAOrder.js'
import approxFlow from '/src/component/assembly/approxFlow.vue'
import toExamine from '/src/component/assembly/toExamine.vue'
import download from '/src/utils/downLoad.js'
import {
  getProcessLog,
  getEnableUserList,
  getStoreMgList,
  getSupplierInfoList,
  getMaterialTypeDetail,
  getMaterialDetail,
  getMaterialTree,
  getNextNodeAssignWay,
} from '/src/http/commonApi.js'

export default {
  components: {
    approxFlow,
    toExamine,
  },
  data() {
    return {
      loading: false,
      draftBtnStatus: false,

      ccListStatus: false,
      manOptions: [],
      ccList: [],
      toExamineData: {
        toExamineDataStatus: false,
        isSearch: false,
      },
      approxForm: {
        approveOperation: '1',

        opinion: '发起了审批',
      },
      steps: {},

      stockName: '',
      orderNum: '',
      recipient: null,
      stockDate: [],

      multipleSelection: [],

      editTitle: '新增',
      innerVisible: false,
      teamTakeStockItems: [],
      innerSelect: [],
      innerAllSelect: [],
      editDialogStatus: false,
      storeOptions: [],
      editForm: {
        stockName: '',
        recipient: null,
        stockDate: '',
        storeId: null,
        remark: '',
        teamTakeStockItems: [],
      },
      rules: {
        stockName: [
          {
            required: true,
            message: '请输入盘点名称',
            trigger: 'change',
          },
        ],
        stockDate: [
          {
            required: true,
            message: '请选择盘点时间',
            trigger: 'change',
          },
        ],
        recipient: [
          {
            required: true,
            message: '请选择领用人',
            trigger: 'change',
          },
        ],
        storeId: [
          {
            required: true,
            message: '请选择仓库名称',
            trigger: 'change',
          },
        ],
      },
      supplierIdRules: [
        {
          required: true,
          message: '请选择供应商',
          trigger: 'change',
        },
      ],
      batchNumRules: [
        {
          required: true,
          message: '请选择批号',
          trigger: 'change',
        },
      ],
      materialIdRules: [
        {
          required: true,
          message: '请选择物料名称',
          trigger: 'change',
        },
      ],
      modelIdRules: [
        {
          required: true,
          message: '请选择规格型号',
          trigger: 'change',
        },
      ],

      stotalInventoryRules: [
        {
          required: true,
          message: '请输入库存合计',
          trigger: 'change',
        },
      ],
      materialInventoryRules: [
        {
          required: true,
          message: '请输入本月原材料库存',
          trigger: 'change',
        },
      ],
      manufacturedInventoryRules: [
        {
          required: true,
          message: '请输入本月成品及半成品库存',
          trigger: 'change',
        },
      ],
      totalVolumeRules: [
        {
          required: true,
          message: '请输入累计领用量',
          trigger: 'change',
        },
      ],

      selectRowArr: [],
      materialArrOptions: [],
      deleteData: [],
      rowId: null,

      dialogVisible: false,
      projectInput: '',
      renderData: [],
      total: 0,
      pageSize: 10,
      pageNum: 1,
      isSearch: false,

      editTitle: '',
      editDialogStatus: false,
      editProjectIdentifyInput: '',
      editProjectInput: '',
      from: {},
    }
  },
  watch: {},
  mounted() {
    this.getTeamTakeStockPageApi()
  },
  methods: {
    draftBtnStatusHandler() {
      this.draftBtnStatus = !this.draftBtnStatus
      this.pageNum = 1
      this.pagSize = 10
      this.getTeamTakeStockPageApi()
    },

    setAggregateAttritionRate(row) {
      row.aggregateAttritionRate = row.aggregateWastage / row.aggregateCompleted
    },

    setWastageAttritionRate(row) {
      setTimeout(() => {
        row.wastageAttritionRate =
          row.constructionWastage / row.constructionCompletedCount
        row.wastageAttritionRate = row.wastageAttritionRate
        row.reduction = row.constructionWastage / row.constructionCompletedCount
        row.reduction = row.reduction.toFixed(2)
      }, 300)
    },

    setWastageExceedCoefficient(row) {
      row.wastageExceedCoefficient =
        Number(row.wastageAttritionRate) -
        Number(row.wastageAttritionCoefficient)

      row.wastageExceedCoefficient = row.wastageExceedCoefficient.toFixed(2)
      this.updateWastageExceedConsumpti(row)
    },

    updateWastageExceedConsumpti(row) {
      row.wastageExceedConsumption =
        row.wastageExceedCoefficient * row.constructionCompletedCount
    },

    searchHandler() {
      this.isSearch = true
      if (
        this.stockName === '' &&
        this.orderNum === '' &&
        this.recipient === null &&
        this.stockDate == []
      ) {
        this.$message({
          message: '请输入查询条件',
          type: 'warning',
        })
      } else {
        this.pageNum = 1
        this.getTeamTakeStockPageApi(
          1,
          this.pageSize,
          this.stockName,
          this.orderNum,
          this.recipient,
          this.stockDate
        )
      }
    },

    resetHandler() {
      this.stockName = ''
      this.orderNum = ''
      this.recipient = null
      this.stockDate = []
      this.isSearch = false
      this.pageNum = 1
      this.pageSize = 10
      this.getTeamTakeStockPageApi()
    },
    shuaxin() {
      this.$router.go(0)
    },

    handleSelectionChange(val) {
      this.multipleSelection = val
    },

    exportHandler() {
      if (this.multipleSelection.length == 0) {
        if (this.isSearch) {
          let params = {
            ids: '',
            stockName: this.stockName,
            orderNum: this.orderNum,
            recipient: this.recipient,
            stockDate: this.stockDate,
          }
          this.getTeamTakeStockExportApi(params)
        } else {
          this.getTeamTakeStockExportApi()
        }
      } else {
        let ids = this.multipleSelection.map((el) => {
          return el.id
        })
        let params = { ids: ids.join(',') }
        this.getTeamTakeStockExportApi(params)
      }
    },

    auditHandler(name = '', data) {
      if (name === 'detail') {
        this.detailName = 'detail'
        this.$confirm(`确认要审核【${data.stockName}】？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            this.approxForm.opinion = ''

            getProcessLog({ id: data.orderId }).then((res) => {
              if (res.code == 200) {
                this.toExamineData.toExamineDataStatus = true
                this.steps = res.data
              } else {
                this.$message.error(res.message)
              }
            })
          })
          .catch(() => {
            this.$message.info('已取消审批')
          })
      } else {
        if (this.multipleSelection.length > 1) {
          this.$message.warning('审批不能选择多条')
          this.multipleSelection = []
        } else if (this.multipleSelection.length == 0) {
          this.$message.warning('未选择物资盘点')
        } else if (this.multipleSelection[0].state === 'draft') {
          this.$message.warning('该物资盘点为草稿，不能进行审批')
        } else if (!this.multipleSelection[0].permission) {
          if (this.multipleSelection[0].state === 'completed') {
            this.$message.warning('该物资盘点已完成审批')
          } else if (this.multipleSelection[0].state === 'terminated') {
            this.$message.warning('该物资盘点已结束审批')
          } else {
            this.$message.warning('无审批权限')
          }
        } else {
          this.$confirm(
            `确认要审核选中的【${this.multipleSelection[0].stockName}】？`,
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }
          )
            .then(() => {
              this.approxForm.opinion = ''

              getProcessLog({ id: this.multipleSelection[0].orderId }).then(
                (res) => {
                  if (res.code == 200) {
                    this.toExamineData.toExamineDataStatus = true
                    this.steps = res.data
                  } else {
                    this.$message.error(res.message)
                  }
                }
              )
            })
            .catch(() => {
              this.$message.info('已取消审批')
            })
        }
      }
    },

    addHandler() {
      this.getStoreMgListApi()
      this.getEnableUserListApi()
      this.editTitle = '新增'
      this.editDialogStatus = true
      this.editForm = {
        stockName: '',
        recipient: null,
        storeId: null,
        stockDate: '',
        remark: '',
        teamTakeStockItems: [],
      }
      this.getMaterialTreeApi()
      if (this.$refs['editForm']) {
        this.$refs['editForm'].resetFields()
      }
    },

    detailHandler(row) {
      this.getStoreMgListApi()
      this.getEnableUserListApi()
      this.editTitle = '详情'
      if (row.state === 'draft') {
        this.isDraft = true
      } else {
        this.isDraft = false
      }

      this.getTeamTakeStockDetailApi(row)
    },

    editHandler(row) {
      this.getStoreMgListApi()
      this.getEnableUserListApi()
      this.editTitle = '编辑'
      this.getTeamTakeStockDetailApi(row)
    },

    deleteHandler(v) {
      this.$confirm('此操作将永久删除该信息?', '提示', {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.renderData = this.renderData.filter((ele) => {
            var flag = false

            for (const key in v) {
              if (ele[key] != v[key]) {
                flag = true
                break
              }
            }
            return flag
          })
          this.$message.success('删除成功')
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },
    cancelHandler(formName) {
      this.editDialogStatus = false
      setTimeout(() => {
        this.$refs[formName].resetFields()
      }, 300)
    },

    handleSizeChange(v) {
      this.pageSize = v
      this.pageNum = 1
      if (this.isSearch === true) {
        this.getTeamTakeStockPageApi(
          1,
          v,
          this.stockName,
          this.orderNum,
          this.recipient,
          this.stockDate
        )
      } else {
        this.getTeamTakeStockPageApi(1, v)
      }
    },

    handleCurrentChange(v) {
      this.pageNum = v
      if (this.isSearch === true) {
        this.getTeamTakeStockPageApi(
          v,
          this.pageSize,
          this.stockName,
          this.orderNum,
          this.recipient,
          this.stockDate
        )
      } else {
        this.getTeamTakeStockPageApi(v, this.pageSize)
      }
    },

    getChange(row, key) {
      row = row.filter((item) => {
        return item.rowId === this.rowId
      })

      if (key === 'select') {
        if (this.flag) return
        this.editForm.teamTakeStockItems = row
      } else if (key === 'list') {
        this.deleteData = row
      } else {
        this.editForm.teamTakeStockItems = []
        this.teamTakeStockItems = []
        this.deleteData = []
      }
    },

    getRowKey(row) {
      console.log('getROWkey::: ', row)
      return row.id
    },

    innerRowClickHandler(row) {
      this.$refs.selectTable.toggleRowSelection(row)
    },

    openInnerDialog() {
      if (!this.editForm.recipient && !this.editForm.storeId) {
        this.$message.info('请选择领用人和仓库')
        return
      }
      if (!this.editForm.storeId) {
        this.$message.info('请选择仓库')
        return
      }
      if (!this.editForm.recipient) {
        this.$message.info('请选择领用人')
        return
      }

      this.innerVisible = true
    },

    addInnerHandler() {
      this.innerVisible = false
    },

    editRowHandler(row) {
      this.$set(row, 'rowStatus', false)
    },

    deteleRowHandler() {
      this.flag = true

      this.deleteData.forEach((i) => {
        this.editForm.teamTakeStockItems.splice(i, 1)

        this.$refs.selectTable.toggleRowSelection(i)
      })

      this.flag = false
    },

    changeMaterial(v, row) {
      if (!row.model) {
        row.modelId = null
      }
      this.getMaterialDetailApi(v[v.length - 1], row)
      this.getMaterialTypeDetailApi(v[v.length - 1], row)
    },
    changeModel(v, row) {
      row.typeOptions.forEach((item) => {
        if (item.id == v) {
          row.unit = item.unit
          row.modelName = item.model
        }
      })
      this.getVerificationSheetApi(
        row.materialId[row.materialId.length - 1],
        v,
        this.editForm.stockDate,
        row
      )
    },
    getModelHandler(e, row) {
      this.getMaterialDetailApi(
        row.materialId[(row.materialId, length - 1)],
        row
      )
    },

    saveDraftHandler(formName) {
      if (this.editTitle === '新增') {
        this.addTeamTakeStockDraftApi(this.editForm)
      } else {
        this.updateTeamTakeStockDraftApi(this.editForm)
      }
    },

    submitHandler(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.ccList = []
          this.getEnableUserListApi()
          this.ccListStatus = true
        } else {
          this.$message.warning('请检查输入项是否填写完整')
          return false
        }
      })
    },

    ccListSumbit() {
      let params = this.editForm
      this.startProcess(params)
    },

    toExamineFun() {
      if (this.detailName == 'detail') {
        this.startProcess(this.editForm)
      } else {
        this.startProcess(this.multipleSelection[0])
      }
    },
    /**
     * 接口
     *
     */

    getEnableUserListApi() {
      getEnableUserList().then((res) => {
        if (res.code == 200) {
          this.manOptions = res.data
        }
      })
    },

    async getTeamTakeStockGetItemApi() {
      this.innerSelect = []

      await this.getChange([], 'delete')

      await this.deteleRowHandler()

      if (this.$refs.selectTable) {
        this.$refs.selectTable.clearSelection()
      }

      if (this.editForm.recipient && this.editForm.storeId) {
        getTeamTakeStockGetItem(
          this.editForm.recipient,
          this.editForm.storeId
        ).then((res) => {
          if (res.code == 200) {
            if (res.data.length == 0) {
              this.$message.info('暂未查询到出库数据')
              this.editForm.teamTakeStockItems = []
              return
            } else {
              this.$message.success('查询到出库数据')

              res.data.forEach((item) => {
                item.rowId = `${this.editForm.recipient}a${this.editForm.storeId}`
                this.rowId = item.rowId
              })
              this.teamTakeStockItems = res.data
              this.editForm.teamTakeStockItems = []
            }
          } else {
            this.$message.error(res.message)
            return
          }
        })
      }
    },

    getStoreMgListApi() {
      getStoreMgList().then((res) => {
        if (res.code == 200) {
          this.storeOptions = res.data
        }
      })
    },

    getSupplierInfoListApi(item) {
      getSupplierInfoList().then((res) => {
        if (res.code == 200) {
          item.supplierOptions = res.data
        }
      })
    },

    getMaterialTreeApi(item) {
      getMaterialTree().then((res) => {
        if (res.code == 200) {
          if (item) {
            this.$set(item, 'materialArrOptions', res.data)
          } else {
            this.materialArrOptions = res.data
          }
        }
      })
    },

    async getMaterialTypeDetailApi(id, row) {
      getMaterialTypeDetail(id).then((res) => {
        if (res.code === 200) {
          if (res.data.parentIds == null) {
            row.materialId = [res.data.pid, res.data.id]
          } else {
            row.materialId = res.data.parentIds.split(',').map(Number)
            row.materialId.shift()
            row.materialId.push(res.data.id)
          }
        }
      })
    },
    async a(str, id, item) {
      await this.getMaterialTreeApi()

      if (str instanceof Array) {
        item.materialId = str
      } else {
        item.materialId = str.split(',').map(Number)
        item.materialId.shift()
        item.materialId.push(id)
      }
    },

    getMaterialDetailApi(id, item) {
      getMaterialDetail(id).then((res) => {
        if (res.code == 200) {
          item.typeOptions = res.data
        }
      })
    },

    getTeamTakeStockPageApi(
      pageNum = 1,
      pageSize = 10,
      stockName = '',
      orderNum = '',
      recipient = null,
      date = []
    ) {
      let params = {}
      if (this.draftBtnStatus) {
        params = {
          pageNum,
          pageSize,
          createBy: this.$store.state.userInfo.id,
          isDraft: this.draftBtnStatus,
        }
      } else {
        if (date.length == 0) {
          params = {
            pageNum,
            pageSize,
            stockName,
            orderNum,
            recipient,
          }
        } else {
          if (date[0] === date[1]) {
            params = {
              pageNum,
              pageSize,
              stockName,
              orderNum,
              recipient,
              stockDate: date[0],
            }
          } else {
            params = {
              pageNum,
              pageSize,
              stockName,
              orderNum,
              recipient,
              stockStartDate: date[0],
              stockEndDate: date[1],
            }
          }
        }
      }
      this.loading = true
      setTimeout(() => {
        getTeamTakeStockPage(params).then((res) => {
          if (res.code == 200) {
            this.renderData = res.data.records
            this.total = res.data.total
            this.loading = false
          }
        })
      }, 300)
    },

    addTeamTakeStockDraftApi(params) {
      if (params.teamTakeStockItems.length == 0) {
        params.teamTakeStockItems = [
          {
            storeId: null,
            storeName: '',
            supplierId: null,
            supplierName: '',
            batchNum: null,
            materialId: null,
            materialName: '',
            modelId: null,
            modelName: '',
            unit: '',
            totalInventory: undefined,
            materialInventory: undefined,
            manufacturedInventory: undefined,
            totalVolume: undefined,
            remark: '',
          },
        ]
      }
      addTeamTakeStockDraft(params).then((res) => {
        if (res.code == 200) {
          this.$message.success('保存草稿成功')
          this.draftBtnStatus = true
          this.pageNum = 1
          this.getTeamTakeStockPageApi(
            1,
            this.pageSize,
            this.orderNum,
            this.stockName,
            this.recipient,
            this.stockDate
          )
          this.editDialogStatus = false
        } else {
          this.$message.error(res.message)
        }
      })
    },

    updateTeamTakeStockDraftApi(params) {
      updateTeamTakeStockDraft(params).then((res) => {
        if (res.code == 200) {
          this.$message.success('编辑草稿成功')
          this.editDialogStatus = false
          this.getTeamTakeStockPageApi(
            this.pageNum,
            this.pageSize,
            this.stockName,
            this.recipient,
            this.stockDate
          )
        } else {
          this.$message.error(res.message)
        }
      })
    },

    deleteTeamTakeStockApi(id) {
      this.$confirm('此操作将永久删除该物资盘点?', '提示', {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          deleteTeamTakeStock(id).then((res) => {
            if (res.code == 200) {
              this.$message.success('删除成功')
              this.pageNum = 1
              this.getTeamTakeStockPageApi(
                1,
                this.pageSize,
                this.stockName,
                this.recipient,
                this.stockDate
              )
            } else {
              this.$message.error(res.message)
            }
          })
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },

    getTeamTakeStockExportApi(params) {
      let loading = this.$loading({
        lock: true,
        text: '导出中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      getTeamTakeStockExport(params)
        .then((res) => {
          download.excel(res, `物资盘点${Date.now()}.xlsx`)

          this.$refs.multipleTable.clearSelection()
          this.multipleSelection = []
          loading.close()
        })
        .catch((err) => {
          this.$message.error('导出失败')
          loading.close()
        })
    },

    startProcess(biDto) {
      let params = {
        state: biDto.state,
        type: 'mlTeamTakeStock',
      }
      if (this.approxForm.approveOperation === '0') {
        this.terminatePlanApi(biDto.id)
      } else if (this.approxForm.approveOperation === '1') {
        getNextNodeAssignWay(params).then((res) => {
          if (res.code == 200) {
            if (!res.data) {
              this.executeTaskPlanApi(0, biDto)
            } else if (res.data.assignWay === 0 || res.data.assignWay === 2) {
              if (biDto.state == 'draft' || biDto.state == undefined) {
                this.addTeamTakeStockApi(biDto)
              } else {
                this.executeTaskPlanApi(0, biDto)
              }
            } else if (res.data.assignWay === 1) {
            }
          } else {
            this.$message.error(res.message)
          }
        })
      }
    },

    addTeamTakeStockApi(params) {
      let a = {
        assignees: [],
        opinion: this.approxForm.opinion,
        ccList: this.ccList,
        biDto: params,
      }

      addTeamTakeStock(a).then((res) => {
        if (res.code == 200) {
          this.$message.success('新增物资盘点并成功发起审批')
          this.ccListStatus = false
          this.draftBtnStatus = false
          this.pageNum = 1
          this.getTeamTakeStockPageApi(
            1,
            this.pageSize,
            this.stockName,
            this.stockDate
          )
          this.editDialogStatus = false
        } else if (res.code == 300) {
          this.ccListStatus = false
          this.$message.error(res.message)
        } else {
          this.$message.error(res.message)
        }
      })
    },

    getTeamTakeStockDetailApi(data) {
      getTeamTakeStockDetail(data.id).then((res) => {
        if (res.code == 200) {
          if (this.editTitle === '新增') {
            this.getTeamTakeStockGetItemApi()
          } else {
            this.editForm = res.data
            this.editForm.teamTakeStockItems.forEach((el) => {
              if (el.manufacturedInventory == null)
                el.manufacturedInventory = undefined
              if (el.totalInventory == null) el.totalInventory = undefined
              if (el.materialInventory == null) el.materialInventory = undefined
              if (el.totalVolume == null) el.totalVolume = undefined
            })
          }
          if (this.$refs['editForm']) {
            this.$refs['editForm'].resetFields()
          }
          this.editDialogStatus = true
        } else {
          this.$message.error(res.message)
        }
      })
      if (data.state !== 'draft') {
        getProcessLog({ id: data.orderId }).then((res) => {
          if (res.code == 200) {
            this.steps = res.data
            this.steps.state = this.editForm.state
          } else {
            this.$message.error(res.message)
          }
        })
      }
    },

    getNextNodeAssignWayApi(state = '', type = 'mlTeamTakeStock') {
      let params = {
        state,
        type,
      }
      getNextNodeAssignWay(params).then((res) => {
        if (res.code == 200) {
          this.editForm.assignees = res.data.assignees
          this.editForm.ccList = res.data.ccList
        } else {
          this.ccListStatus = false
          this.$message.error(res.message)
        }
      })
    },

    terminatePlanApi(id) {
      terminatePlan(id).then((res) => {
        if (res.code == 200) {
          this.$message.success('终止成功')
          this.toExamineData.toExamineDataStatus = false
          this.editDialogStatus = false

          this.$refs.multipleTable.clearSelection()
          this.multipleSelection = []
          this.getTeamTakeStockPageApi(
            this.pageNum,
            this.pageSize,
            this.stockName,
            this.stockDate
          )
        } else {
          this.$message.error(res.message)
        }
      })
    },
    toExamineDataClean() {
      this.toExamineData = {
        toExamineDataStatus: false,
        isSearch: false,
      }
      this.approxForm = {
        approveOperation: '1',
        opinion: '',
      }
    },

    executeTaskPlanApi(type, biDto) {
      if (type == 0) {
        let params = {
          assignees: [],
          opinion: this.approxForm.opinion,
          ccList: this.ccList,
          biDto,
        }
        executeTaskPlan(params).then((res) => {
          if (res.code == 200) {
            this.$message.success('审核成功')
            this.getTeamTakeStockPageApi(
              this.pageNum,
              this.pageSize,
              this.stockName,
              this.stockDate
            )
            this.editDialogStatus = false
            this.toExamineData.toExamineDataStatus = false

            this.$refs.multipleTable.clearSelection()
            this.multipleSelection = []
          } else {
            this.$message.error(res.message)
          }
        })
      } else {
        this.toExamineData.toExamineDataStatus = false
        this.editDialogStatus = false
        this.terminatePlanApi(biDto.id)
      }
    },
  },
}
</script>

<style lang="less" scoped>
#materSectionSuperAnalysis {
  width: 95%;
  margin: 0 auto;
  margin-top: 1rem;
}
.el-date-editor {
  margin: 0 10px;
}
.imgBox {
  position: relative;
  top: 0;
  left: 0;
  .uploadImg {
    position: absolute;
    top: 30%;
    left: 30%;
    visibility: hidden;
  }
}
.imgBox:hover .uploadImg {
  visibility: visible;
}
:deep(.el-dialog__header) {
  background-color: rgb(43, 43, 53);
}
:deep(.el-dialog__title) {
  color: #fff;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.pDiv {
  background-color: #f5f7fa;
  color: #909399;
  border: 1px solid #dcdfe6;
  border-right: 0px;
  border-radius: 4px 0 0 4px;
  text-align: center;
  height: 40px;
  line-height: 40px;
  width: 13.7%;
}
:deep(.pSelect) {
  .el-input__inner {
    border-radius: 0 4px 4px 0;
    width: 107.5%;
  }
  .el-input__suffix {
    right: -5%;
  }
}
.mgb-10 {
  margin-bottom: 10px;
}

.dialogItem {
  float: left;
}
:deep(.el-input.is-disabled .el-input__inner) {
  color: #606266;
  background-color: #f8f6f6;
}
:deep(.el-textarea.is-disabled .el-textarea__inner) {
  color: #606266;
  background-color: #f8f6f6;
}
</style>
